package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper ;


    @Override
    @Transactional
    public ShoppingCart addCart(ShoppingCart shoppingCart) {

        //根据用户id,或者菜品id,套餐id来查看购物车是否已经有这条数据，要是有就是修改数量，没有就是添加数据
        ShoppingCart shoppingCart1 = shoppingCartMapper.findByUserIdAndDishIdAndSetmealId(shoppingCart);
        //要是不是空的，就添加数量
        if( shoppingCart1 != null ){
            //有数据就修改数量就行
            Integer number = shoppingCart1.getNumber();
            shoppingCart1.setNumber( number + 1 );
            shoppingCart = shoppingCart1 ;
            shoppingCartMapper.Update(shoppingCart1);
        }else{
            //要是是空的，就添加数据
            //要设置参数
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.addShoppingCart(shoppingCart);
        }

        return shoppingCart ;

    }

    @Override
    public List<ShoppingCart> list(Long userId) {

       List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectByUserId(userId);
        return shoppingCartList ;

    }
}
